package wli.web.servlet;

import java.io.IOException;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import wli.hibernate.db.Category;
import wli.hibernate.db.ForumThread;
import wli.hibernate.util.HibernateUtil;
import wli.java.file.util.FileStructure;
import wli.web.util.TextToHtml;

/**
 * Servlet implementation class TopServlet
 */
@WebServlet("/TopServlet")
public class TopServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public TopServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(true);
		PrintWriter out = response.getWriter();

		String username = request.getRemoteUser();

		if (request.getRemoteUser() != null) {
			if (request.getParameter("vcname") != null
					&& request.getParameter("vcid") != null
					&& (request.getParameter("delete") != null && request
							.getParameter("delete").equals("1"))) {
				deleteCategory(Integer.parseInt(request.getParameter("vcid")));
			}
		}

		/**
		 * This section will trig main page display adding category form
		 */
		String new_category = request.getParameter("new_category");
		if (new_category != null && new_category.length() > 0
				&& request.getParameter("Add") != null
				&& request.getParameter("Add").equals("ADD")
				&& request.getRemoteUser() != null) {
			request.setAttribute("top_main", "add_category");
			session.setAttribute("ADD_CATEGORY_FORM_ID",
					System.currentTimeMillis());
		}

		/**
		 * this section will save catgory
		 */

		if (request.getParameter("add_category") != null
				&& request.getParameter("category_name") != null
				&& request.getParameter("category_name").length() > 0
				&& request.getParameter("add_category_form_id") != null
				&& request.getParameter("add_category_form_id")
						.equals(session.getAttribute("ADD_CATEGORY_FORM_ID")
								.toString())) {
			if (getTotalCategory(username) < 20) {
				System.out.println("Total Category:" + getTotalCategory());
				if (addCategory((1 + getNextCategoryId()),
						request.getParameter("category_name"),
						request.getParameter("category_description"), username,
						"wli", "") > 0) {
					session.setAttribute("ADD_CATEGORY_FORM_ID", 100);
					request.setAttribute("top_main", "add_category_ok");
				}
			} else {
				request.setAttribute("top_main", "add_category_over_limit");
			}
		}


		ArrayList alist = (ArrayList) getCategoryList(username);
		// out.println(alist);
		out.println("<table width=100%><tr>");
		Iterator<Category> its = alist.iterator();
		Category cat = null;
		while (its.hasNext()) {
			cat = (Category) its.next();
			out.println("<td align=center><input type=button onClick=\"location.href='?vcid="
					+ cat.getCategory_id()
					+ "&vcname="
					+ cat.getName()
					+ "'\" value='" + cat.getName() + "'></td>");
			request.setAttribute("Category-Description", cat.getDescription());
		}

		if (request.getRemoteUser() == null) {
			out.println("<td align=center><input type=button onClick=\"location.href='members'\" value='Add'></td>");
		} else {
			out.println("<form><td align=center>");
			out.println("<TABLE><TR>");
			out.println("<TD><input type=text name=new_category size=15 maxsize=20></TD>");
			out.println("<TD><input type=submit name=Add value=ADD></TD>");
			out.println("<TD><input type=submit name=Edit value=EDIT></TD>");
			out.println("</TR></TABLE>");
			out.println("</td></form>");
		}

		if (request.getRemoteUser() == null) {
			out.println("<td align=center><input type=button onClick=\"location.href='members'\" value='Sign In'></td>");
			out.println("<td align=center><input type=button onClick=\"location.href='?vmaid=1'\" value='Create an account'></td>");
		} else {
			out.println("<td align=center><input type=button onClick=\"location.href='signout'\" value='Welcome:  "
					+ request.getRemoteUser() + "'></td>");
			out.println("<td align=center><input type=button onClick=\"location.href='?signout=true'\" value='Sign out'></td>");
		}
		out.println("</tr></table>");

		// RequestDispatcher dispatcher =
		// request.getRequestDispatcher("top.jsp");
		// dispatcher.include(request, response);
	}

	private List<Category> getCategoryList(String username) {
		Session hsession = null;
		Transaction transaction = null;
		Category cat = null;
		List<Category> clist = new ArrayList<Category>();
		try {

			hsession = HibernateUtil.getSessionFactory().openSession();
			// transaction = hsession.beginTransaction();
			Criteria criteria = hsession.createCriteria(Category.class);
			clist = criteria.add(Restrictions.eq("owner", username)).list();
			// clist = criteria.list();
			// Collections.sort(flist);
			Iterator<Category> its = clist.iterator();
			String apace = null;
			while (its.hasNext()) {
				cat = (Category) its.next();
				System.out.println("category_id=" + cat.getCategory_id());
			}
		} catch (HibernateException e) {

		}
		return clist;
	}

	private int getTotalCategory() {
		Session hsession = null;
		Transaction transaction = null;
		Category cat = null;
		List<Category> clist = new ArrayList<Category>();
		try {

			hsession = HibernateUtil.getSessionFactory().openSession();
			Criteria criteria = hsession.createCriteria(Category.class);
			// clist = criteria.add(Restrictions.eq("owner", username)).list();
			clist = criteria.list();
			// Collections.sort(flist);

		} catch (HibernateException e) {

		}
		return clist.size();
	}

	private int getTotalCategory(String username) {
		Session hsession = null;
		Transaction transaction = null;
		Category cat = null;
		List<Category> clist = new ArrayList<Category>();
		try {

			hsession = HibernateUtil.getSessionFactory().openSession();
			Criteria criteria = hsession.createCriteria(Category.class);
			clist = criteria.add(Restrictions.eq("owner", username)).list();
			// clist = criteria.list();
			// Collections.sort(flist);

		} catch (HibernateException e) {

		}
		return clist.size();
	}

	private int getNextCategoryId() {
		Session hsession = null;
		Transaction transaction = null;
		Category cat = null;
		List<Category> clist = new ArrayList<Category>();
		try {

			hsession = HibernateUtil.getSessionFactory().openSession();
			Criteria criteria = hsession.createCriteria(Category.class);
			clist = criteria.list();
			// clist = criteria.list();
			//Collections.sort(clist);

			return (clist.get(0)).getCategory_id();

		} catch (HibernateException e) {

		}
		return clist.size();
	}

	private Category getSingleCategory(String cat_id) {
		Category cate;

		Session hsession = null;
		Transaction transaction = null;
		try {

			hsession = HibernateUtil.getSessionFactory().openSession();
			Criteria criteria = hsession.createCriteria(ForumThread.class);
			List<Category> clist = new ArrayList<Category>();
			clist = criteria.add(
					Restrictions.eq("category_id", Integer.parseInt(cat_id)))
					.list();

			Iterator<Category> its = clist.iterator();
			String apace = null;
			while (its.hasNext()) {
				cate = (Category) its.next();
				if (cate.getCategory_id() == (Integer.parseInt(cat_id))) {
					return cate;
				}
			}
		} catch (HibernateException e) {
			System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
					+ e);
		} finally {
			hsession.close();
		}

		return null;
	}

	private int deleteCategory(int category_id) {

		Session hsession = null;
		Transaction transaction = null;

		try {
			hsession = HibernateUtil.getSessionFactory().openSession();
			transaction = hsession.beginTransaction();
			/*
			 * System.out.println(">>>>>>>>>"+hsession.createCriteria(Category.class
			 * ).add( Restrictions.eq("categoryId", category_id)));
			 */

			Category category = new Category();

			List<Category> clist = new ArrayList<Category>();
			Criteria criteria = hsession.createCriteria(Category.class);
			clist = criteria.add(Restrictions.eq("category_id", category_id))
					.list();
			category = clist.get(0);
			hsession.delete(category);

			transaction.commit();
			return 1;

		} catch (HibernateException e) {
			transaction.rollback();
			e.printStackTrace();
		} finally {
			hsession.close();
		}
		return -1;
	}

	private int addCategory(int cat_id, String name, String description,
			String owner, String manager, String group_access) {

		Session hsession = null;
		Transaction transaction = null;

		try {
			hsession = HibernateUtil.getSessionFactory().openSession();

			Category categ = new Category();
			categ.setCategory_id(cat_id);
			categ.setName(name);
			categ.setDescription(description);
			categ.setOwner(owner);
			categ.setManager(manager);
			categ.setGroup_access(group_access);
			categ.setDate_create(new java.sql.Date(System.currentTimeMillis()));

			hsession = HibernateUtil.getSessionFactory().openSession();
			transaction = hsession.beginTransaction();

			hsession.save(categ);
			transaction.commit();
			return 1;

		} catch (HibernateException e) {
			transaction.rollback();
			e.printStackTrace();
		} finally {
			hsession.close();
		}
		return -1;
	}
}
